<script setup>
import { ref } from "vue";
import { Plus, Upload } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores";
import { patchUserUpdateAvatar } from "@/api/user";

const userStore = useUserStore();

const uploadRef = ref(null); // 上传组件引用

// 预览头像
const imgUrl = ref("");
// 上传的头像
const avatarUrl = ref(userStore.userInfo.avatarUrl);

// 上传文件选择后的回调
const onUploadFile = (file) => {
  // 将文件转换成 base64
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    avatarUrl.value = reader.result;
  };
};
// 上传头像（实际调用接口的逻辑）
const handleUpload = async () => {
  if (!avatarUrl.value) {
    ElMessage({
      message: "请选择图片",
      type: "warning",
      plain: true,
    });
    return;
  }
  const res = await patchUserUpdateAvatar({ avatarUrl: avatarUrl.value });

  ElMessage({
    message: "上传成功",
    type: "success",
  });

  // 更新store数据
  userStore.getUserInfo();
};

// 触发文件选择（兼容不同版本的写法）
const triggerFileSelect = () => {
  if (!uploadRef.value) return;

  try {
    // 方式1：适用于大部分版本（直接触发上传组件的点击）
    uploadRef.value.click();
  } catch (e) {
    try {
      // 方式2：备选方案（获取内部input元素触发）
      const input = uploadRef.value.$el.querySelector('input[type="file"]');
      if (input) input.click();
    } catch (e2) {
      console.error("触发文件选择失败:", e2);
    }
  }
};
</script>

<template>
  <Card title="更换头像">
    <el-row>
      <el-col :span="12">
        <!-- 上传组件：保持原有的图片预览逻辑 -->
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
        >
          <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
          <img v-else src="@/assets/avatar.jpg" width="278" />
        </el-upload>
        <br />
        <!-- 选择图片按钮：绑定触发方法 -->
        <el-button
          type="primary"
          :icon="Plus"
          size="large"
          @click="triggerFileSelect"
        >
          选择图片
        </el-button>
        <!-- 上传头像按钮：绑定上传逻辑 -->
        <el-button
          type="success"
          :icon="Upload"
          size="large"
          @click="handleUpload"
        >
          上传头像
        </el-button>
      </el-col>
    </el-row>
  </Card>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
      object-fit: cover; /* 图片自适应容器 */
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
  }
}
</style>
